package com.insight.modules.system.controller;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.constant.CacheConstant;
import com.insight.common.system.query.QueryGenerator;
import com.yuanqiao.insight.acore.system.entity.SysDictItem;
import com.yuanqiao.insight.acore.system.service.ISysDictItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @Author zhangweijian
 * @since 2018-12-28
 */
@RestController
@RequestMapping("/sys/dictItem")
@Slf4j
public class SysDictItemController {

    @Autowired
    private ISysDictItemService sysDictItemService;

    /**
     * 分页查询字典数据
     * 支持根据字典项文本模糊查询，结果按排序字段升序排列
     *
     * @param sysDictItem 查询条件实体，支持部分字段过滤
     * @param pageNo      当前页码，默认1
     * @param pageSize    每页条数，默认10
     * @param req         HttpServletRequest，获取请求参数
     * @return 分页封装的字典项列表
     */
    @AutoLog(value = "数据字典-查询字典配置")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysDictItem>> queryPageList(SysDictItem sysDictItem,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {

        // 先暂存 itemText 参数，避免被 QueryGenerator 初始化覆盖
        String itemText = sysDictItem.getItemText();
        sysDictItem.setItemText("");
        Result<IPage<SysDictItem>> result = new Result<>();

        // 使用QueryGenerator根据请求参数自动生成查询条件
        QueryWrapper<SysDictItem> queryWrapper = QueryGenerator.initQueryWrapper(sysDictItem, req.getParameterMap());

        // 如果前端传了itemText，增加模糊查询条件
        if (StringUtils.isNotEmpty(itemText)) {
            queryWrapper.like("item_text", itemText);
        }

        // 按sort_order字段升序排序
        queryWrapper.orderByAsc("sort_order");

        // 构造分页对象
        Page<SysDictItem> page = new Page<>(pageNo, pageSize);

        // 执行分页查询
        IPage<SysDictItem> pageList = sysDictItemService.page(page, queryWrapper);

        // 封装结果
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 新增字典配置项
     * 会校验字典项名称是否重复（同一字典内）
     * 同时清理相关缓存
     *
     * @param sysDictItem 字典配置实体
     * @return 新增结果，成功或失败提示
     */
    @AutoLog(value = "数据字典-新增字典配置")
    //@RequiresRoles({"admin"})  // 需要管理员权限可放开
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYSDICT_ITEM__CACHE}, allEntries = true)
    public Result<SysDictItem> add(@RequestBody SysDictItem sysDictItem) {
        Result<SysDictItem> result = new Result<>();
        try {
            if (sysDictItem == null || sysDictItem.getItemText() == null || sysDictItem.getDictId() == null) {
                return result.error500("请求参数为空");
            }
            if (sysDictItemService != null) {
                List<SysDictItem> list = sysDictItemService.list(new QueryWrapper<SysDictItem>()
                        .eq("item_text", sysDictItem.getItemText())
                        .eq("dict_id", sysDictItem.getDictId()));
                if (CollUtil.isNotEmpty(list)) {
                    result.error500("字典配置项名称重复！");
                    return result;
                }
                sysDictItem.setCreateTime(new Date());
                sysDictItemService.save(sysDictItem);
            }
            result.success("保存成功！");
        } catch (Exception e) {
            log.error("新增字典配置异常：", e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑字典配置项
     * 校验同字典内排除自身后，名称不重复
     * 同时清理缓存
     *
     * @param sysDictItem 编辑后的字典配置实体
     * @return 编辑结果
     */
    @AutoLog(value = "数据字典-编辑字典配置")
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYSDICT_ITEM__CACHE}, allEntries = true)
    public Result<SysDictItem> edit(@RequestBody SysDictItem sysDictItem) {
        Result<SysDictItem> result = new Result<>();
        // 查询同一字典中，排除当前项的重复名称
        List<SysDictItem> list = sysDictItemService.list(new QueryWrapper<SysDictItem>()
                .ne("id", sysDictItem.getId())
                .eq("item_text", sysDictItem.getItemText())
                .eq("dict_id", sysDictItem.getDictId()));
        if (CollUtil.isNotEmpty(list)) {
            result.error500("字典配置项名称重复！");
            return result;
        }
        // 设置更新时间
        sysDictItem.setUpdateTime(new Date());
        // 更新数据
        sysDictItemService.updateById(sysDictItem);
        result.success("编辑成功!");
        return result;
    }

    /**
     * 删除单个字典配置
     * 同时清理缓存
     *
     * @param id 字典配置ID
     * @return 删除结果
     */
    @AutoLog(value = "数据字典-删除字典配置")
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYSDICT_ITEM__CACHE}, allEntries = true)
    public Result<SysDictItem> delete(@RequestParam(name = "id", required = true) String id) {
        Result<SysDictItem> result = new Result<>();
        SysDictItem joinSystem = sysDictItemService.getById(id);
        if (joinSystem == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = sysDictItemService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    /**
     * 批量删除字典配置项
     * 同时清理缓存
     *
     * @param ids 逗号分隔的字典配置ID列表
     * @return 删除结果
     */
    //@RequiresRoles({"admin"})
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    @CacheEvict(value = {CacheConstant.SYS_DICT_CACHE, CacheConstant.SYSDICT_ITEM__CACHE}, allEntries = true)
    public Result<SysDictItem> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<SysDictItem> result = new Result<>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            // 转成集合，批量删除
            this.sysDictItemService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

}

